package http

import http.request.*
import korlibs.io.net.http.*
import kotlinx.serialization.*
import kotlinx.serialization.json.*

class PointsHttpClient(serverIp: String, private val id: String) {
    private val url = "http://$serverIp:8080/points"
    private val json = Json

    suspend fun addPoints(house: String, points: Int) {
        HttpRestClient(createHttpClientEndpoint("$url/$house"))
            .post("", json.encodeToString(AddPoints(id, points)))
    }

    suspend fun houses(): Boolean {
        return try {
            HttpRestClient(createHttpClientEndpoint("$url/all")).get("").toString().isNotEmpty()
        } catch (e: Exception) {
            false
        }
    }

    suspend fun login(name: String): String? {
        return try {
            HttpRestClient(createHttpClientEndpoint("$url/professor"))
                .post("", json.encodeToString(LoginData(name))).toString()
        } catch (e: Http.HttpException) {
            null
        }
    }
}
